package com.jyxd.web.task;

import com.alibaba.fastjson.JSON;
import com.jyxd.web.data.basic.QuartzTask;
import com.jyxd.web.data.basic.QuartzTime;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.service.assessment.basic.QuartzTaskService;
import com.jyxd.web.service.assessment.basic.QuartzTimeService;
import com.jyxd.web.service.assessment.basic.VitalSignMergeService;
import com.jyxd.web.service.patient.PatientService;
import com.jyxd.web.util.CompareTimeUtil;
import com.jyxd.web.util.DateUtil;
import com.jyxd.web.util.SpringUtil;
import com.jyxd.web.util.UUIDUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时同步生命体征任务
 */
public class VitalSignsJob implements Job {
    private static Logger logger = LoggerFactory.getLogger(VitalSignsJob.class);
    //定义一个成员变量
    private static QuartzTask quartzTask;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        QuartzTime quartzTime = new QuartzTime();
        quartzTime.setStartTime(new Date());
        ServletContext context = null;
        logger.info("开始同步生命体征");
        CronExpression expression = null;
        try {
            //获取service
            context = (ServletContext) jobExecutionContext.getScheduler().getContext().get(QuartzServletContextListener.MY_CONTEXT_NAME);
            WebApplicationContext cxt = (WebApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            QuartzTimeService quartzTimeService = (QuartzTimeService) cxt.getBean("quartzTimeService");
            QuartzTaskService quartzTaskService = (QuartzTaskService) cxt.getBean("quartzTaskService");
            VitalSignMergeService vitalSignMergeService = SpringUtil.getBean(VitalSignMergeService.class);
            PatientService patientService = SpringUtil.getBean(PatientService.class);
            List<Patient> patients = patientService.queryPatientByFlagAndBed("");
            if (!CollectionUtils.isEmpty(patients)) {
                String time = DateUtil.yyyyMMddHHmmSdfToString(new Date());
                Map<String, String> map = new HashMap<String, String>();
                map.put("time", time);
                for (Patient patient : patients) {
                    map.put("patientId", patient.getId());
                    logger.info("time: " + time + "  --  patientId: " + patient.getId());
                    HttpResult httpResult = vitalSignMergeService.syncVitalSignMerge(map, null);
                    logger.info(JSON.toJSONString(httpResult));
                }
                logger.info("已完成本次同步 ：" + time);
            }


            //操作定时任务执行记录表
            Map<String, Object> map = new HashMap<>();
            map.put("jobName", "VitalSignsJob");
            map.put("jobGroup", "VitalSignsJob");
            quartzTask = quartzTaskService.queryDataByNameAndGroup(map);
            expression = new CronExpression(quartzTask.getCron());
            quartzTime.setNextTime(expression.getNextValidTimeAfter(quartzTime.getStartTime()));
            quartzTime.setQuartzTaskId(quartzTask.getId());
            quartzTime.setId(UUIDUtil.getUUID());
            quartzTime.setEndTime(new Date());
            quartzTime.setTimeLength(String.valueOf(CompareTimeUtil.calculatetimeGapSecond(quartzTime.getStartTime(), quartzTime.getEndTime())));
            quartzTime.setStatus(1);
            quartzTimeService.insert(quartzTime);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
